package town;

import game.Game;
import game.GameDriver;
import game.ResourceBasket;
import game.Round;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;

/**
 * Pub is a building in town that lets you gamble for money. The amount of money
 * won is greater than zero, and is directly related to how much time is left in
 * the round. The more time left, the more money won. Gambling ends the players
 * turn.
 * 
 * @author Bradley
 */
public class Pub extends TownBuilding {

    /** Auto-generated serial version ID. */
    private static final long serialVersionUID = 2388394569685616614L;

    private JButton gamble;
    private JLabel winnings;


    public Pub(Game currentGame, GameDriver driver, Round round) {
	super(currentGame, driver, round);

	gamble = new JButton(new ImageIcon(this.getClass().getResource("/images/gamble.png")));
	gamble.setBorder(null);
	gamble.setOpaque(false);
	gamble.setToolTipText("Gamble to win money and end your turn");
	gamble.addActionListener(new ButtonListener(driver));
	
	winnings = new JLabel();
	winnings.setFont(winnings.getFont().deriveFont(25.0f));
	//winnings.setForeground(Color.WHITE);
	building.add(gamble, BorderLayout.NORTH);
	building.add(winnings, BorderLayout.SOUTH);
    }

    /**
     * ButtonListener for the Gamble JButton.
     * 
     * @author Bradley
     */
    class ButtonListener implements ActionListener {
	private ResourceBasket basket;
	private GameDriver driver;
	private Random rand;

	public ButtonListener(GameDriver driver) {
	    this.driver = driver;
	    rand = new Random();
	}

	/**
	 * When the user presses the Gamble button, he gets a psuedo random
	 * amount of money as described in the top of this file. The turn ends.
	 */
	public void actionPerformed(ActionEvent e) {
	    this.basket = round.getCurrPlayerResourceBasket();
	    int money = rand.nextInt(10) * 2 + round.getSecondsLeft() + 10;
	    basket.addResource(4, money);
	    winnings.setText("You won $" + money + "!");
	    winnings.setBorder(null);
	    winnings.setOpaque(false);

	    round.updateInfoPanel();
	    if (round.getPlayerInt() + 1 == currentGame.playerArraySize()
	    		&& currentGame.getPhase() > 0) {
	    	    currentGame.sortPlayerArray();
	    	}
	    round.incrementPlayerInt();
	    round.takeTurn();
	    driver.toPanel(round.getMapPanel(), BorderLayout.CENTER);
	    winnings.setText("");

	}

    }

   }

